package com.wtb.rr.servlet;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wtb.pub.WtbException;
import com.wtb.pub.WtbBaseServlet;
import com.wtb.rr.domain.RrDetailInfo;
import com.wtb.rr.domain.RrOauth;
import com.wtb.utils.RrTokenUtils;

public class RrOauthServlet extends WtbBaseServlet {
	private static final Log log = LogFactory.getLog(RrOauthServlet.class);
	private static final long serialVersionUID = 1L;
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		RrOauth rrOauth = null;
		RrDetailInfo rrDetailInfo = null;
		RrTokenUtils rrTokenUtils = new RrTokenUtils();
		try {
			//获取accessToken
			rrOauth = rrTokenUtils.getAccessToken(request, response);
			//关闭授权窗口 直接返回
			if (rrOauth.getUni().equals("code")) {
				response.sendRedirect("");
				return;
			}
			if (rrOauth == null) {
				throw new WtbException("获取AccessToken失败！");
			}
			//获取用户信息
			rrDetailInfo = rrTokenUtils.getUserInfo(rrOauth);
			if (rrDetailInfo.getUser() == null) {
				throw new WtbException("获取用户信息失败！");
			}
		} catch (Exception e) {
			log.error("人人用户授权失败：", e);
			response.sendRedirect("error?err_code=1002");
			return;
		}
		HttpSession session = request.getSession();
		HashMap<String, Object> lastMap = (HashMap<String, Object>) session.getAttribute("lastMap");
		if (lastMap == null) {
			lastMap = new HashMap<String, Object>();
		}
		if (lastMap.size() == 2) {
			lastMap.clear();
		}
		lastMap.put("rr", rrDetailInfo);
		session.setAttribute("lastMap", lastMap);
		session.setAttribute("status", null);
		response.sendRedirect("last");
	}
}
